﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using NuGetServer.Models;
namespace NuGetServer.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Package()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Helpers.GetBaseUrl(Request.Url, Request.ApplicationPath) + "nuget/Packages");
            XmlNamespaceManager xn = new XmlNamespaceManager(doc.NameTable);
            xn.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
            xn.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            xn.AddNamespace("ns", "http://www.w3.org/2005/Atom");
            XmlNodeList xNodes = doc.SelectNodes("/ns:feed/ns:entry", xn);
            List<NuGetPackage> packages = new List<NuGetPackage>();
            foreach (XmlNode node in xNodes)
            {
                packages.Add(new NuGetPackage()
                {
                    Title = node.SelectSingleNode("ns:title", xn).InnerText,
                    Author = node.SelectSingleNode("ns:author", xn).InnerText,
                    UpdateDate = DateTime.Parse(node.SelectSingleNode("ns:updated", xn).InnerText),
                    Version = node.SelectSingleNode("m:properties/d:Version", xn).InnerText,
                    Description = node.SelectSingleNode("m:properties/d:Description", xn).InnerText,
                    PublishedDate = DateTime.Parse(node.SelectSingleNode("m:properties/d:Published", xn).InnerText)
                });
            }
            return View(packages.OrderByDescending(p => p.UpdateDate));
        }

        public ActionResult Delete(string id)
        {
            var filePath = Server.MapPath("/Packages/" + id);

            System.IO.File.Delete(filePath);

            return RedirectToAction("Package");
        }

    }
}
